<script setup>
import { ref } from 'vue'
import { useTaskStore } from '../stores/03.state(组合式)'
import { storeToRefs } from 'pinia'

// 获取store实例
const taskStore = useTaskStore()

// 使用storeToRefs保持响应性
const { tasks, user, settings } = storeToRefs(taskStore)

// 新任务标题
const newTaskTitle = ref('')

// 添加新任务
function addTask() {
  if (newTaskTitle.value.trim()) {
    taskStore.addTask(newTaskTitle.value.trim())
    newTaskTitle.value = ''
  }
}

// 用户信息表单
const userForm = ref({
  name: '',
  role: ''
})

// 更新用户信息
function updateUser() {
  if (userForm.value.name || userForm.value.role) {
    taskStore.updateUser({
      name: userForm.value.name || user.value.name,
      role: userForm.value.role || user.value.role
    })
    userForm.value = { name: '', role: '' }
  }
}

// 设置表单
const settingsForm = ref({
  darkMode: settings.value.darkMode,
  notifications: settings.value.notifications,
  language: settings.value.language
})

// 更新设置
function updateSettings() {
  taskStore.updateSettings({
    darkMode: settingsForm.value.darkMode,
    notifications: settingsForm.value.notifications,
    language: settingsForm.value.language
  })
}
</script>

<template>
  <div class="tutorial-container">
    <header>
      <h1>03.state(组合式)</h1>
      <p class="subtitle">学习如何在组合式API中定义和使用state</p>
      
      <nav class="tutorial-nav">
        <router-link to="/01" class="nav-link">01.认识pinia</router-link>
        <router-link to="/02" class="nav-link">02.定义store(选项式)</router-link>
        <router-link to="/02c" class="nav-link">02.定义store(组合式)</router-link>
        <router-link to="/03" class="nav-link">03.state(选项式)</router-link>
        <router-link to="/03c" class="nav-link">03.state(组合式)</router-link>
        <router-link to="/04" class="nav-link">04.getters(选项式)</router-link>
        <router-link to="/04c" class="nav-link">04.getters(组合式)</router-link>
        <router-link to="/05" class="nav-link">05.actions(选项式)</router-link>
        <router-link to="/05c" class="nav-link">05.actions(组合式)</router-link>
      </nav>
    </header>

    <main>
      <section class="intro">
        <h2>什么是State?</h2>
        <p>在Pinia中，state是store的核心部分，它定义了store中存储的数据。state是一个返回初始状态的函数，这确保了在服务器端渲染(SSR)时的状态隔离。</p>
        
        <div class="code-example">
          <pre><code>// 定义一个带有state的store
export const useStore = defineStore('storeId', {
  state: () => ({
    // 所有这些属性都将自动推断出它们的类型
    count: 0,
    name: 'Eduardo',
    isAdmin: true,
    items: [],
    user: {
      name: '',
      isAuthenticated: false
    }
  })
})</code></pre>
        </div>
      </section>

      <div class="demo-section">
        <div class="tasks-section">
          <h2>任务管理示例</h2>
          
          <!-- 任务列表 -->
          <div class="card">
            <h3>任务列表</h3>
            
            <!-- 添加任务表单 -->
            <div class="task-form">
              <input 
                v-model="newTaskTitle" 
                type="text" 
                placeholder="输入新任务..." 
                @keyup.enter="addTask"
              />
              <button @click="addTask" class="btn primary">添加任务</button>
            </div>
            
            <!-- 任务列表 -->
            <div v-if="tasks.length > 0" class="tasks-list">
              <div v-for="task in tasks" :key="task.id" class="task-item">
                <div class="task-content">
                  <input 
                    type="checkbox" 
                    :checked="task.completed" 
                    @change="taskStore.toggleTask(task.id)"
                  />
                  <span :class="{ completed: task.completed }">{{ task.title }}</span>
                </div>
                <button @click="taskStore.removeTask(task.id)" class="btn danger small">删除</button>
              </div>
            </div>
            <div v-else class="empty-list">
              <p>没有任务</p>
            </div>
            
            <!-- 任务操作 -->
            <div v-if="tasks.length > 0" class="task-actions">
              <button @click="taskStore.resetTasksStatus(false)" class="btn secondary">全部标记为未完成</button>
              <button @click="taskStore.resetTasksStatus(true)" class="btn secondary">全部标记为已完成</button>
            </div>
          </div>
          
          <!-- 用户信息 -->
          <div class="card">
            <h3>用户信息</h3>
            
            <div class="user-info">
              <p><strong>姓名:</strong> {{ user.name }}</p>
              <p><strong>角色:</strong> {{ user.role }}</p>
            </div>
            
            <div class="user-form">
              <h4>更新用户信息</h4>
              <div class="form-group">
                <label>姓名</label>
                <input v-model="userForm.name" type="text" placeholder="输入新姓名" />
              </div>
              <div class="form-group">
                <label>角色</label>
                <input v-model="userForm.role" type="text" placeholder="输入新角色" />
              </div>
              <button @click="updateUser" class="btn primary">更新信息</button>
            </div>
          </div>
          
          <!-- 应用设置 -->
          <div class="card">
            <h3>应用设置</h3>
            
            <div class="settings-form">
              <div class="form-group checkbox">
                <input 
                  id="darkMode" 
                  v-model="settingsForm.darkMode" 
                  type="checkbox"
                />
                <label for="darkMode">暗黑模式</label>
              </div>
              
              <div class="form-group checkbox">
                <input 
                  id="notifications" 
                  v-model="settingsForm.notifications" 
                  type="checkbox"
                />
                <label for="notifications">启用通知</label>
              </div>
              
              <div class="form-group">
                <label>语言</label>
                <select v-model="settingsForm.language">
                  <option value="zh-CN">中文</option>
                  <option value="en-US">英文</option>
                  <option value="ja-JP">日文</option>
                </select>
              </div>
              
              <button @click="updateSettings" class="btn primary">保存设置</button>
            </div>
          </div>
        </div>
      </div>
      
      <section class="explanation">
        <h2>组合式API中使用State</h2>
        
        <div class="subsection">
          <h3>1. 访问State</h3>
          <p>在组合式API中，你可以直接从store实例访问state属性：</p>
          <div class="code-example">
            <pre><code>import { useStore } from './store'

// 在组件中
export default {
  setup() {
    const store = useStore()
    
    // 直接访问state
    console.log(store.count)
    
    // 也可以使用解构，但会失去响应性
    const { name } = store
    
    return {
      // 将整个store暴露给模板
      store
    }
  }
}</code></pre>
          </div>
        </div>
        
        <div class="subsection">
          <h3>2. 使用storeToRefs保持响应性</h3>
          <p>如果你想解构store中的属性但又想保持响应性，可以使用<code>storeToRefs</code>：</p>
          <div class="code-example">
            <pre><code>import { useStore } from './store'
import { storeToRefs } from 'pinia'

export default {
  setup() {
    const store = useStore()
    
    // 使用storeToRefs解构，保持响应性
    const { count, name, user } = storeToRefs(store)
    
    // actions可以直接解构，不需要storeToRefs
    const { increment } = store
    
    return {
      count,
      name,
      user,
      increment
    }
  }
}</code></pre>
          </div>
        </div>
        
        <div class="subsection">
          <h3>3. 修改State</h3>
          <p>在组合式API中，你可以直接修改state属性：</p>
          <div class="code-example">
            <pre><code>import { useStore } from './store'

export default {
  setup() {
    const store = useStore()
    
    // 直接修改state
    store.count++
    store.name = '新名称'
    
    // 修改嵌套对象
    store.user.name = '张三'
    
    // 替换整个state对象
    store.$state = {
      count: 0,
      name: '重置',
      user: { name: '', isAuthenticated: false }
    }
    
    // 部分更新state
    store.$patch({
      count: store.count + 1,
      name: '部分更新'
    })
    
    // 使用函数更新state（适合复杂更新）
    store.$patch((state) => {
      state.count++
      state.name = '函数更新'
      state.items.push({ id: state.nextId++, name: '新项目' })
    })
    
    return { store }
  }
}</code></pre>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<style scoped>
.tutorial-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

header {
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
}

h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 20px;
}

.tutorial-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 20px;
}

.nav-link {
  padding: 8px 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.2s;
}

.nav-link:hover {
  background-color: #e0e0e0;
}

.intro {
  margin-bottom: 40px;
}

.code-example {
  background-color: #f8f8f8;
  border-radius: 6px;
  padding: 15px;
  margin: 15px 0;
  overflow-x: auto;
}

pre {
  margin: 0;
}

code {
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
}

.demo-section {
  margin-bottom: 40px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.task-form {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.task-form input {
  flex: 1;
}

.tasks-list {
  margin-bottom: 20px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.task-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.completed {
  text-decoration: line-through;
  color: #999;
}

.task-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.user-info {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.user-form h4 {
  margin-bottom: 15px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group.checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-group.checkbox input {
  width: auto;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group.checkbox label {
  margin-bottom: 0;
}

input, select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

select {
  background-color: white;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.btn.primary {
  background-color: #4CAF50;
  color: white;
}

.btn.primary:hover {
  background-color: #3e8e41;
}

.btn.secondary {
  background-color: #f1f1f1;
  color: #333;
}

.btn.secondary:hover {
  background-color: #e0e0e0;
}

.btn.danger {
  background-color: #f44336;
  color: white;
}

.btn.danger:hover {
  background-color: #d32f2f;
}

.btn.small {
  padding: 4px 8px;
  font-size: 0.9rem;
}

.empty-list {
  text-align: center;
  padding: 20px;
  color: #666;
}

.explanation {
  margin-top: 40px;
}

.subsection {
  margin-bottom: 30px;
}
</style>
